package edu.qichen.onlineBlog.file.controller;

import cn.hutool.core.util.StrUtil;
import edu.qichen.onlineBlog.framework.AuthAccess;
import edu.qichen.onlineBlog.framework.DataResult;
import edu.qichen.onlineBlog.framework.exception.BusinessException;
import edu.qichen.onlineBlog.framework.exception.ErrorCodeEnum;
import edu.qichen.onlineBlog.framework.utils.OSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 功能:测试OSS上传
 * 作者:程序员欧阳子韩
 * 日期:2024/5/13 16:54
 */
@Slf4j
@RestController
public class uploadController {
    @Autowired
    private OSSUtils ossUtils;

    /**
     * 上传图片
     *
     * @param image -
     * @return -
     * @throws IOException -
     */
    @PostMapping("/upload")
    public DataResult<?> upload(MultipartFile image) throws IOException {
        try {
            log.info("文件上传，文件名{}", image.getOriginalFilename());

            // 调用阿里云OSS工具类进行文件上传
            String url = ossUtils.picOSS(image);


            if (StrUtil.isBlank(url)) {
                log.error("文件上传失败，未获得有效的URL");
                throw BusinessException.build(ErrorCodeEnum.FILE_UPLOAD_ERROR);
            }
            log.info("文件上传完成，url:{}", url);

            return DataResult.success(url);
        } catch (Exception e) {
            log.error("文件上传发生异常", e);
            return DataResult.fail("文件上传失败，发生异常：" + e.getMessage());
        }
    }
}
